//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package alarm_dao

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"atomgit.com/openlinksaas/proto-gen-go.git/project_alarm_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type ConfigDbItem struct {
	ProjectId              string `bson:"_id"`
	EnableIssueDependCheck bool   `bson:"enableIssueDependCheck"`
	IssueDependHitValue    uint32 `bson:"issueDependHitValue"`
	IssueDependAlertValue  uint32 `bson:"issueDependAlertValue"`
	EnableIssueDelayCheck  bool   `bson:"enableIssueDelayCheck"`
	IssueDelayHitValue     uint32 `bson:"issueDelayHitValue"`
	IssueDelayAlertValue   uint32 `bson:"issueDelayAlertValue"`
	EnableIssueReOpenCheck bool   `bson:"enableIssueReOpenCheck"`
	IssueReOpenHitValue    uint32 `bson:"issueReOpenHitValue"`
	IssueReOpenAlertValue  uint32 `bson:"issueReOpenAlertValue"`
	// EnableScriptErrorCheck  bool   `bson:"inableScriptErrorCheck"`
	// EnableEarthlyErrorCheck bool   `bson:"inableEarthlyErrorCheck"`
}

func (item *ConfigDbItem) ToConfig() *project_alarm_api.Config {
	return &project_alarm_api.Config{
		EnableIssueDependCheck: item.EnableIssueDependCheck,
		IssueDependHitValue:    item.IssueDependHitValue,
		IssueDependAlertValue:  item.IssueDependAlertValue,
		EnableIssueDelayCheck:  item.EnableIssueDelayCheck,
		IssueDelayHitValue:     item.IssueDelayHitValue,
		IssueDelayAlertValue:   item.IssueDelayAlertValue,
		EnableIssueReOpenCheck: item.EnableIssueReOpenCheck,
		IssueReOpenHitValue:    item.IssueReOpenHitValue,
		IssueReOpenAlertValue:  item.IssueReOpenAlertValue,
	}
}

type _ConfigDao struct {
	mc *mongo.Collection
}

func newConfigDao(db *mongo.Database) (*_ConfigDao, error) {
	mc := db.Collection(db_ns.DB_NS_PROJECT_ALARM + "config")
	return &_ConfigDao{mc: mc}, nil
}

func (db *_ConfigDao) Set(ctx context.Context, dbItem *ConfigDbItem) error {
	_, err := db.mc.UpdateByID(ctx, dbItem.ProjectId, bson.M{"$set": dbItem}, options.Update().SetUpsert(true))
	return err
}

func (db *_ConfigDao) Get(ctx context.Context, projectId string) (*ConfigDbItem, error) {
	retItem := &ConfigDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": projectId}).Decode(retItem)
	return retItem, err
}
